package afcp.alumni.security;

import javax.servlet.http.HttpServletRequest;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.ExecutionContext;
import net.sourceforge.stripes.controller.Interceptor;
import net.sourceforge.stripes.controller.Intercepts;
import net.sourceforge.stripes.controller.LifecycleStage;
import afcp.alumni.action.base.BaseAction;
import afcp.alumni.action.base.MyActionBeanContext;
import afcp.alumni.action.event.LoginAction;
import afcp.alumni.action.page.ChangePasswordAction;
import afcp.alumni.model.db.Member;

@Intercepts(value = LifecycleStage.HandlerResolution)
public class ChangePasswordInterceptor implements Interceptor {

	@Override
	public Resolution intercept(ExecutionContext context) throws Exception {
		ActionBean from = context.getActionBean();

		if (!(from instanceof ChangePasswordAction)
				&& !(from instanceof LoginAction)) {
			Member member = ((MyActionBeanContext) context
					.getActionBeanContext()).getUser();
			if (member != null && !member.isPasswordChanged()) {
				ForwardResolution forward = new ForwardResolution(
						ChangePasswordAction.class);
				if (from instanceof BaseAction) {
					forward.addParameter(ChangePasswordAction.FROM_PARAM,
							((BaseAction) from).getUrl());
				}
				return forward;
			}
		}

		return context.proceed();
	}

	protected String getRequestedPath(HttpServletRequest request) {
		String servletPath = request.getServletPath();
		String pathInfo = request.getPathInfo();
		return (servletPath == null ? "" : servletPath)
				+ (pathInfo == null ? "" : pathInfo);
	}

}
